package com.itheima.stock.secuity.service;

import com.google.common.base.Strings;
import com.itheima.stock.face.UserRolePermissionService;
import com.itheima.stock.face.impl.StockCacheFaceImpl;
import com.itheima.stock.mapper.SysUserMapper;
import com.itheima.stock.mapper.SysUserRoleMapper;
import com.itheima.stock.pojo.SysPermission;
import com.itheima.stock.pojo.SysRole;
import com.itheima.stock.pojo.SysUser;
import com.itheima.stock.vo.req.UserMenus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: siwukun
 * @date: 2022/06/15
 * @description:
 */
@Component
public class LoginUserDetailService implements UserDetailsService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private UserRolePermissionService userRolePermissionService;
    /**
     * 登录类
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {

        SysUser user = sysUserMapper.findByUsernamePassword(name);
        if (user==null){
            throw  new RuntimeException("用户名不存在");
        }
     /*   //拿到用户的id查询用户对应的权限信息
        List<SysPermission> permissions = sysUserMapper.selectAllUser(user.getId());
        //获取权限集合permsList
        final List<String> permsList = permissions.stream().filter(item -> !Strings.isNullOrEmpty(item.getPerms())).map(item -> item.getPerms()).collect(
                Collectors.toList()
        );
        //获取角色的权限
        List<SysRole> listRole = sysUserRoleMapper.selectByUserPrimaryKey(user.getId());
        final List<String> roleName = listRole.stream().filter(role -> !Strings.isNullOrEmpty(role.getName())).map(role -> "ROLE_" + role.getName()).collect(
                Collectors.toList()
        );
        List<String> auths = new ArrayList<>();
        auths.addAll(permsList);
        auths.addAll(roleName);*/
        //拿到用户的id查询用户对应的权限信息
        List<SysPermission> permissions = sysUserMapper.selectAllUser(user.getId());
        //获取用户对应的权限 角色信息 用缓存处理stockCacheFace
         List<String> auths = userRolePermissionService.getUserRoleAndPermissionInfo(user.getId());
        //把auths转化为数组
        final String[] toArray = auths.toArray(new String[auths.size()]);
        //把toArray，赋给springSecurity
        List<GrantedAuthority> authorityList = AuthorityUtils.createAuthorityList(toArray);
        //设置用户权限信息
        user.setAuthorities(authorityList);
        //获取权限树，响应给前端
        //组装权限树和获取菜单按钮集合
        userRolePermissionService.getMenus(user,permissions);
//        //获取菜单按钮集合
//        List<String> authBtnPerms = permissions.stream()
//                .filter(per -> !Strings.isNullOrEmpty(per.getCode()) && per.getType() == 3)
//                .map(per -> per.getCode()).collect(Collectors.toList());
//        user.setPermissions(authBtnPerms);
        return user;
    }

    //组装数据
    private List<UserMenus> menuEcho(List<SysPermission> allUser, String id, Boolean isForMenus) {
        List<UserMenus> list = new ArrayList<>();
        for (SysPermission permission : allUser) {
            if(permission!=null && permission.getType()!=3 || !isForMenus){
                //获取permissionId
                String permissionId = permission.getId();
                //获取pid
                String pid = permission.getPid();
                if (pid!=null){
                    if (pid.equals(id)){
                        UserMenus userMenus = new UserMenus();
                        userMenus.setId(permission.getId());
                        userMenus.setTitle(permission.getTitle());
                        userMenus.setIcon(permission.getIcon());
                        userMenus.setPath(permission.getUrl());
                        userMenus.setName(permission.getName());
                        userMenus.setChildren(menuEcho(allUser,permissionId,isForMenus));
                        list.add(userMenus);
                    }
                }
            }
        }
        return list;
    }

    /**
     * 缓存处理获取用户对应的权限 角色信息
     */
    public List<String> getUserRoleAndPermissionInfo(String uid){
        //拿到用户的id查询用户对应的权限信息
        List<SysPermission> permissions = sysUserMapper.selectAllUser(uid);
        //获取权限集合permsList
        final List<String> permsList = permissions.stream().filter(item -> !Strings.isNullOrEmpty(item.getPerms())).map(item -> item.getPerms()).collect(
                Collectors.toList()
        );
        //获取角色的权限
        List<SysRole> listRole = sysUserRoleMapper.selectByUserPrimaryKey(uid);
        final List<String> roleName = listRole.stream().filter(role -> !Strings.isNullOrEmpty(role.getName())).map(role -> "ROLE_" + role.getName()).collect(
                Collectors.toList()
        );
        List<String> auths = new ArrayList<>();
        auths.addAll(permsList);
        auths.addAll(roleName);
        return auths;
    }

    /**
     * 用户前端侧边栏信息缓存和获取菜单按钮集合
     * @param sysUser
     * @param permissions
     */
    public  void getMenus(SysUser sysUser,List<SysPermission> permissions){
        List<UserMenus> list = menuEcho(permissions, "0",true);
        List<String> authBtnPerms = permissions.stream()
                .filter(per -> !Strings.isNullOrEmpty(per.getCode()) && per.getType() == 3)
                .map(per -> per.getCode()).collect(Collectors.toList());
        sysUser.setPermissions(authBtnPerms);
        sysUser.setMenus(list);
    }
}
